package com.codedancer.campus.client.service.impl;

import com.codedancer.campus.client.service.IEmailService;
import com.codedancer.campus.client.service.bo.email.SendEmailBo;
import com.codedancer.campus.common.model.mail.EmailSendModel;
import com.codedancer.campus.common.utils.EmailUtil;
import com.codedancer.campus.common.utils.RedisUtil;
import com.codedancer.campus.common.utils.VerificationCodeUtil;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class EmailServiceImpl implements IEmailService {


    @Autowired
    private EmailUtil emailUtil;
    @Autowired
    private RedisUtil redisUtil;
    @Resource(name = "smsRedisTemplate")
    private StringRedisTemplate stringRedisTemplate;
    @Value("${start.campus.redis.register.email.key}")
    private String registerEmailKey;

    /**
     * 发送验证码
     *
     * @param sendEmailBo
     */
    @Override
    public void sendCode(SendEmailBo sendEmailBo) {
        redisUtil.setRedisTemplate(stringRedisTemplate);
        String code = VerificationCodeUtil.getSixCode();
        EmailSendModel sendModel = new EmailSendModel();
        List<String> receiversEmails = new ArrayList<>();
        receiversEmails.add(sendEmailBo.getEmail());
        sendModel.setReceiverEmails(receiversEmails);
        sendModel.setSubject("邮箱注册验证码");
        sendModel.setContent("您好:\n"
            + "\n本次注册的邮件验证码为:" + code
            + ",本验证码 5 分钟内效，请及时输入。（请勿泄露此验证码）\n"
            + "\n如非本人操作，请忽略该邮件。\n(这是一封通过自动发送的邮件，请不要直接回复）");
        emailUtil.sendEmailCode(sendModel);
        redisUtil.setStringValueAndTime(registerEmailKey + sendEmailBo.getEmail(), code, 300L);
    }
}
